<template>


	<div>
		<el-upload class="avatar-uploader" action="#" :show-file-list="false" :http-request="handleUpload" :before-upload="beforeAvatarUpload">
			<img v-if="imageUrl" :src="imageUrl" class="avatar">
			<i v-else class="el-icon-plus avatar-uploader-icon"></i>
		</el-upload>

		<div style="margin: 50px;"></div>
		<el-form :label-position="right" label-width="80px" :model="formLabelAlign" :style="{ width: '500px',margin: '0 auto'}">
			<el-form-item label="用户名">
				<el-input v-model="formLabelAlign.username" :disabled="true"></el-input>
			</el-form-item>
			<el-form-item label="电话">
				<el-input v-model="formLabelAlign.phone"></el-input>
			</el-form-item>
			<el-form-item label="邮箱">
				<el-input v-model="formLabelAlign.email"></el-input>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="submitForm('formLabelAlign')">提交</el-button>
				<el-button @click="resetForm('formLabelAlign')">重置</el-button>
				<el-button @click="EditPassword()">修改密码</el-button>
			</el-form-item>
		</el-form>


	</div>



</template>




<script>
	import Cookies from "js-cookie";

	export default {
		data() {
			return {
				imageUrl: '',
				loginName: '',
				labelPosition: 'right',
				formLabelAlign: {
					username: '',
					phone: '',
					email: ''
				}
			}
		},
		mounted() {

			this.loginName = Cookies.get("loginName");
			// 初始化时加载头像
			this.loadAvatar();
			this.loadForm();

		},
		methods: {
			// 加载头像（带时间戳防缓存）
			loadAvatar() {
				this.imageUrl = `http://localhost:8088/file/download?loginName=${this.loginName}&t=${Date.now()}`;
			},
			loadForm() {
				let _this = this;
				this.$axios
					.get("/user/getInfo", {
						params: {
							loginName: this.loginName
						}
					})
					.then(function(response) {

						_this.formLabelAlign.username = response.data.username;
						_this.formLabelAlign.phone = response.data.phone;
						_this.formLabelAlign.email = response.data.email;

						// console.log('接口返回数据：', response.data); // 查看实际数据结构
					})
					.catch(console.error);
			},
			handleUpload(file) {
				//todo: 修改前先删除原先的图片
				let formData = new FormData();
				let _this = this; // 保存当前上下文

				formData.append('file', file.file);

				formData.append('loginName', this.loginName);
				for (const pair of formData.entries()) {
					console.log(pair[0], pair[1]);
				}

				this.$axios
					.post(
						`http://localhost:8088/file/upload`, // 参数放在URL
						formData,
						// headers: { 'Content-Type': 'multipart/form-data;boundary = ' + new Date().getTime() }
						{
							// 'Content-Type': 'multipart/form-data;boundary = ${formData._boundary}'
							// headers: {
							// 	'Content-Type': 'multipart/form-data'
							// }
						})
					.then(function(response) {
						if (response.data) {
							_this.$message.success('头像上传成功');
							_this.loadAvatar(); // 使用保存的上下文引用
						}
					})
					.catch(function(error) {
						console.error('上传失败:', error);
						_this.$message.error('头像上传失败');
					});
			},
			// 上传前校验
			beforeAvatarUpload(file) {
				const isImage = ['image/jpeg', 'image/png'].includes(file.type);
				const isLt10M = file.size / 1024 / 1024 < 10;

				if (!isImage) {
					this.$message.error('只能上传 JPG/PNG 格式的图片!');
				}
				if (!isLt10M) {
					this.$message.error('图片大小不能超过 10MB!');
				}

				return isImage && isLt10M;
			},
			submitForm(formName) {
				// 发送请求到后端，使用data传递请求体
				this.$axios.put('/user', {
						params: {
							phone: this.formLabelAlign.phone,
							email: this.formLabelAlign.email
						}
					})
					.then(response => {
						console.log('Response received from server:');
						console.log('Response data:', response.data);

						if (response.data) {
							this.$message.success('信息更新成功');
							console.log('信息更新成功');
							this.loadUserData(); // 更新数据
						} else {
							this.$message.error('信息更新失败: ' + response.data.message);
							console.log('信息更新失败: ' + response.data.message);
						}
					})
					.catch(error => {
						console.error('Error during form submission:', error);
						this.$message.error('保存失败: ' + (error.response?.data?.message || '服务器错误'));
					});
			},
			resetForm(formName) {
				// this.$refs[formName].resetFields();
				this.loadForm();
			},
			EditPassword() {
				this.$router.push("/main/password");
			}


		}


	}
</script>

<style>
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}

	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
</style>
